#!/usr/bin/env python3
"""
初始化商品数据
"""
import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from app.db.database import SessionLocal
from app.models.product import Product, ProductDetail
from app.models.category import Category

def init_products():
    db = SessionLocal()
    try:
        # 获取分类
        categories = db.query(Category).all()
        if not categories:
            print("❌ 请先运行 init_data.py 创建分类")
            return
        
        # 检查是否已有商品
        existing_products = db.query(Product).count()
        if existing_products > 0:
            print("✅ 商品数据已存在，跳过初始化")
            return
        
        # 创建测试商品
        products_data = [
            {
                "name": "iPhone 15 Pro",
                "description": "最新款iPhone，搭载A17 Pro芯片，支持5G网络",
                "price": 7999.00,
                "original_price": 8999.00,
                "category_id": 1,  # 电子产品
            },
            {
                "name": "MacBook Air M2",
                "description": "轻薄便携的笔记本电脑，搭载M2芯片",
                "price": 8999.00,
                "original_price": None,
                "category_id": 1,  # 电子产品
            },
            {
                "name": "时尚休闲T恤",
                "description": "舒适透气的纯棉T恤，多种颜色可选",
                "price": 99.00,
                "original_price": 129.00,
                "category_id": 2,  # 服装
            },
            {
                "name": "牛仔裤",
                "description": "经典款牛仔裤，修身显瘦",
                "price": 199.00,
                "original_price": None,
                "category_id": 2,  # 服装
            },
            {
                "name": "北欧风格沙发",
                "description": "简约现代的三座沙发，舒适耐用",
                "price": 2999.00,
                "original_price": 3999.00,
                "category_id": 3,  # 家居
            },
            {
                "name": "智能台灯",
                "description": "可调节亮度的LED台灯，护眼设计",
                "price": 299.00,
                "original_price": None,
                "category_id": 3,  # 家居
            },
            {
                "name": "Python编程从入门到实践",
                "description": "畅销的Python编程教程，适合初学者",
                "price": 89.00,
                "original_price": 99.00,
                "category_id": 4,  # 图书
            },
            {
                "name": "JavaScript高级程序设计",
                "description": "JavaScript经典教程，深入浅出",
                "price": 129.00,
                "original_price": None,
                "category_id": 4,  # 图书
            },
        ]
        
        for product_data in products_data:
            product = Product(**product_data)
            db.add(product)
            print(f"✅ 创建商品: {product_data['name']}")
        
        db.commit()
        print("✅ 商品数据初始化完成!")
        
    except Exception as e:
        print(f"❌ 初始化失败: {e}")
        db.rollback()
    finally:
        db.close()

if __name__ == "__main__":
    init_products() 